<template>
  <div class="chat-container container">
    <div class="page-title">
      <h2>在线客服</h2>
    </div>
    
    <div class="chat-box card">
      <div class="chat-header">
        <div class="service-info">
          <el-avatar :size="40" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"></el-avatar>
          <div class="service-detail">
            <div class="service-name">客服小王</div>
            <div class="service-status online">在线</div>
          </div>
        </div>
      </div>
      
      <div class="chat-messages" ref="messageBox">
        <div v-for="(message, index) in messages" :key="index" :class="['message', message.type]">
          <template v-if="message.type === 'service'">
            <el-avatar :size="36" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"></el-avatar>
            <div class="message-content">
              <div class="message-text">{{ message.content }}</div>
              <div class="message-time">{{ message.time }}</div>
            </div>
          </template>
          <template v-else>
            <div class="message-content">
              <div class="message-text">{{ message.content }}</div>
              <div class="message-time">{{ message.time }}</div>
            </div>
            <el-avatar :size="36" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
          </template>
        </div>
      </div>
      
      <div class="chat-input">
        <el-input
          type="textarea"
          :rows="3"
          placeholder="请输入消息..."
          v-model="inputMessage"
          @keyup.enter.native="sendMessage"
        ></el-input>
        <div class="input-actions">
          <el-button type="primary" @click="sendMessage" :disabled="!inputMessage.trim()">发送</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ServiceChat',
  data() {
    return {
      inputMessage: '',
      messages: [
        {
          type: 'service',
          content: '您好，我是客服小王，很高兴为您服务，请问有什么可以帮助您的吗？',
          time: this.formatTime(new Date())
        }
      ],
      websocket: null,
      sessionId: null,
      userId: null,
      serviceId: 1, // 默认客服ID
      heartbeatTimer: null,
      reconnectTimer: null,
      reconnectAttempts: 0,
      maxReconnectAttempts: 5
    }
  },
  created() {
    // 获取用户ID，实际项目中应从登录用户信息中获取
    this.userId = localStorage.getItem('userId') || Math.floor(Math.random() * 1000000);
    localStorage.setItem('userId', this.userId);
  },
  mounted() {
    this.connectWebSocket();
    this.scrollToBottom();
  },
  updated() {
    this.scrollToBottom();
  },
  beforeDestroy() {
    // 关闭WebSocket连接
    this.closeWebSocket();
  },
  methods: {
    sendMessage() {
      if (!this.inputMessage.trim()) return;
      
      // 添加用户消息
      const userMessage = {
        type: 'user',
        content: this.inputMessage,
        time: this.formatTime(new Date())
      };
      this.messages.push(userMessage);
      
      // 发送消息到服务器
      if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
        const message = {
          type: 'CHAT',
          sessionId: this.sessionId,
          receiverId: this.serviceId,
          content: this.inputMessage,
          timestamp: Date.now()
        };
        this.websocket.send(JSON.stringify(message));
      } else {
        // WebSocket未连接，使用自动回复
        setTimeout(() => {
          this.receiveServiceMessage(this.getAutoReply(this.inputMessage));
        }, 1000);
      }
      
      // 清空输入框
      this.inputMessage = '';
    },
    receiveServiceMessage(content) {
      const serviceMessage = {
        type: 'service',
        content,
        time: this.formatTime(new Date())
      };
      this.messages.push(serviceMessage);
    },
    formatTime(date) {
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const messageBox = this.$refs.messageBox;
        if (messageBox) {
          messageBox.scrollTop = messageBox.scrollHeight;
        }
      });
    },
    getAutoReply(message) {
      // 简单的自动回复逻辑
      const lowerMessage = message.toLowerCase();
      
      if (lowerMessage.includes('你好') || lowerMessage.includes('hi') || lowerMessage.includes('hello')) {
        return '您好，请问有什么可以帮助您的吗？';
      }
      
      if (lowerMessage.includes('价格') || lowerMessage.includes('多少钱') || lowerMessage.includes('费用')) {
        return '我们的租车价格根据车型不同而有所差异，经济型轿车一般每天200-300元，SUV每天300-500元，豪华车型每天500元起。具体价格请在车辆详情页查看。';
      }
      
      if (lowerMessage.includes('押金') || lowerMessage.includes('保证金')) {
        return '我们的押金政策是：经济型轿车2000元，中高级轿车3000-5000元，豪华车型10000元起。押金在还车时会全额退还（如无违章和车辆损伤）。';
      }
      
      if (lowerMessage.includes('取车') || lowerMessage.includes('还车') || lowerMessage.includes('门店')) {
        return '您可以在我们全国各大城市的门店取还车，目前已覆盖北京、上海、广州、深圳等50多个城市，200多家门店。具体门店地址可在下单时选择查看。';
      }
      
      if (lowerMessage.includes('证件') || lowerMessage.includes('驾驶证') || lowerMessage.includes('身份证')) {
        return '租车需要提供本人有效身份证和驾驶证原件，驾驶证需要满一年以上，部分高端车型要求3年以上驾龄。';
      }
      
      if (lowerMessage.includes('保险') || lowerMessage.includes('责任险')) {
        return '我们所有车辆均已购买交强险和商业险，您可以选择额外购买租车险以减少您的责任。';
      }
      
      if (lowerMessage.includes('违章') || lowerMessage.includes('罚单')) {
        return '租车期间产生的交通违章由承租人负责，我们会在还车时检查违章情况，如有违章需要支付违章押金，待处理完成后多退少补。';
      }
      
      if (lowerMessage.includes('谢谢') || lowerMessage.includes('感谢')) {
        return '不客气，很高兴能帮到您！如果还有其他问题，随时咨询我。';
      }
      
      return '您的问题我已收到，稍后会有专业客服人员与您联系解答。您也可以拨打我们的客服热线：400-123-4567，获取更多帮助。';
    },
    
    // WebSocket相关方法
    connectWebSocket() {
      // 检查浏览器是否支持WebSocket
      if ('WebSocket' in window) {
        // 创建WebSocket连接
        const wsUrl = `ws://${window.location.hostname}:8086/service/ws/chat/${this.userId}/1`;
        this.websocket = new WebSocket(wsUrl);
        
        // 连接成功
        this.websocket.onopen = () => {
          console.log('WebSocket连接成功');
          this.reconnectAttempts = 0;
          
          // 发送心跳包
          this.startHeartbeat();
          
          // 发送连接消息
          const connectMessage = {
            type: 'CONNECT',
            senderId: this.userId,
            senderType: 1,
            timestamp: Date.now()
          };
          this.websocket.send(JSON.stringify(connectMessage));
        };
        
        // 接收消息
        this.websocket.onmessage = (event) => {
          const message = JSON.parse(event.data);
          console.log('收到消息:', message);
          
          // 处理不同类型的消息
          switch (message.type) {
            case 'CONNECT':
              // 连接成功，保存会话ID
              if (message.sessionId) {
                this.sessionId = message.sessionId;
              }
              break;
            case 'CHAT':
              // 接收聊天消息
              if (message.senderType === 2) { // 客服消息
                this.receiveServiceMessage(message.content);
              }
              break;
            case 'HEARTBEAT':
              // 心跳响应，不做处理
              break;
            default:
              break;
          }
        };
        
        // 连接关闭
        this.websocket.onclose = () => {
          console.log('WebSocket连接关闭');
          this.stopHeartbeat();
          
          // 尝试重连
          if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectTimer = setTimeout(() => {
              this.reconnectAttempts++;
              console.log(`尝试第${this.reconnectAttempts}次重连`);
              this.connectWebSocket();
            }, 3000);
          }
        };
        
        // 连接错误
        this.websocket.onerror = (error) => {
          console.error('WebSocket连接错误:', error);
        };
      } else {
        console.error('浏览器不支持WebSocket');
      }
    },
    
    closeWebSocket() {
      if (this.websocket) {
        // 发送关闭消息
        const closeMessage = {
          type: 'CLOSE',
          sessionId: this.sessionId,
          senderId: this.userId,
          senderType: 1,
          timestamp: Date.now()
        };
        
        try {
          this.websocket.send(JSON.stringify(closeMessage));
        } catch (e) {
          console.error('发送关闭消息失败:', e);
        }
        
        // 关闭连接
        this.websocket.close();
        this.websocket = null;
        
        // 停止心跳
        this.stopHeartbeat();
        
        // 清除重连定时器
        if (this.reconnectTimer) {
          clearTimeout(this.reconnectTimer);
          this.reconnectTimer = null;
        }
      }
    },
    
    startHeartbeat() {
      this.heartbeatTimer = setInterval(() => {
        if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
          const heartbeatMessage = {
            type: 'HEARTBEAT',
            timestamp: Date.now()
          };
          this.websocket.send(JSON.stringify(heartbeatMessage));
        }
      }, 30000); // 30秒发送一次心跳
    },
    
    stopHeartbeat() {
      if (this.heartbeatTimer) {
        clearInterval(this.heartbeatTimer);
        this.heartbeatTimer = null;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.chat-container {
  padding: 20px 0;
  
  .page-title {
    margin-bottom: 20px;
    
    h2 {
      font-size: 24px;
      font-weight: 500;
      color: #303133;
      margin: 0;
    }
  }
  
  .card {
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
  }
  
  .chat-box {
    display: flex;
    flex-direction: column;
    height: 70vh;
    min-height: 500px;
  }
  
  .chat-header {
    padding: 15px 20px;
    border-bottom: 1px solid #ebeef5;
    
    .service-info {
      display: flex;
      align-items: center;
      
      .service-detail {
        margin-left: 10px;
        
        .service-name {
          font-size: 16px;
          font-weight: 500;
          color: #303133;
        }
        
        .service-status {
          font-size: 12px;
          
          &.online {
            color: #67c23a;
            
            &:before {
              content: '';
              display: inline-block;
              width: 6px;
              height: 6px;
              border-radius: 50%;
              background-color: #67c23a;
              margin-right: 5px;
            }
          }
        }
      }
    }
  }
  
  .chat-messages {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    background-color: #f5f7fa;
    
    .message {
      display: flex;
      margin-bottom: 20px;
      
      &.service {
        align-items: flex-start;
        
        .el-avatar {
          margin-right: 10px;
        }
        
        .message-content {
          .message-text {
            background-color: #fff;
            color: #606266;
            border-radius: 0 8px 8px 8px;
          }
        }
      }
      
      &.user {
        justify-content: flex-end;
        align-items: flex-start;
        
        .el-avatar {
          margin-left: 10px;
        }
        
        .message-content {
          align-items: flex-end;
          
          .message-text {
            background-color: #409eff;
            color: #fff;
            border-radius: 8px 0 8px 8px;
          }
          
          .message-time {
            text-align: right;
          }
        }
      }
      
      .message-content {
        max-width: 70%;
        display: flex;
        flex-direction: column;
        
        .message-text {
          padding: 10px 15px;
          word-break: break-word;
          line-height: 1.5;
        }
        
        .message-time {
          font-size: 12px;
          color: #909399;
          margin-top: 5px;
        }
      }
    }
  }
  
  .chat-input {
    padding: 15px 20px;
    border-top: 1px solid #ebeef5;
    
    .input-actions {
      display: flex;
      justify-content: flex-end;
      margin-top: 10px;
    }
  }
}

@media (max-width: 768px) {
  .chat-container {
    .chat-box {
      height: calc(100vh - 150px);
    }
    
    .chat-messages {
      .message {
        .message-content {
          max-width: 85%;
        }
      }
    }
  }
}
</style> 